<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="项目状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择项目状态">
          <el-option v-for="dict in dict.type.pro_plan_status" :key="dict.value" :label="dict.label"
            :value="parseInt(dict.value)"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="责任人" prop="duty">
        <el-input v-model="queryParams.duty" placeholder="请输入责任人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="登记团队" prop="registrant">
        <el-select v-model="queryParams.registrant" placeholder="请选择登记团队">
          <el-option v-for="item in teamList" :key="item.teamTeamname" :label="item.teamTeamname"
            :value="item.teamTeamname"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="queryParams.priority" placeholder="请选择优先级">
          <el-option v-for="dict in dict.type.pro_plan_level" :key="dict.value" :label="dict.label"
            :value="parseInt(dict.value)"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:plan:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:plan:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:plan:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:plan:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目编号" align="center" prop="projectId" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="计划开始日期" align="center" prop="planStartDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planStartDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划完成日期" align="center" prop="planCompleteDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planCompleteDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划工作内容" align="center" prop="planWorkContent" width="180" />
      <el-table-column label="实际开始时间" align="center" prop="actualStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.actualStartTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际结束时间" align="center" prop="actualEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.actualEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pro_plan_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="工作计划用时" align="center" prop="workPlanTime" width="180"
        :formatter="formatWorkCompleteTime" />
      <el-table-column label="工作完成用时" align="center" prop="workCompleteTime" width="180"
        :formatter="formatWorkCompleteTime" />
      <!-- <el-table-column label="目前耗时" align="center" prop="consumTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.consumTime) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="责任人" align="center" prop="duty" />
      <el-table-column label="登记团队" align="center" prop="registrant" />
      <el-table-column label="优先级" align="center" prop="priority">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pro_plan_level" :value="scope.row.priority" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="子级任务标志" align="center" prop="childTaskFlag" width="180" /> -->
      <el-table-column label="确认完成时间" align="center" prop="confirmCompleteTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.confirmCompleteTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目完成确认人" align="center" prop="planConfirmer" width="180" />
      <el-table-column label="备注" align="center" prop="remake" width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:plan:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:plan:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-check" @click="handleOk(scope.row)"
            v-hasPermi="['system:plan:edit']">确认项目</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改项目计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1100px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">

        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作计划用时-[天]" prop="workPlanTime">
              <el-input-number v-model="form.workPlanTime" controls-position="right" :min="1"
                :max="36500"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="计划开始日期" prop="planStartDate">
              <el-date-picker v-model="form.planStartDate" :picker-options="pickerOptionsStart" @change="changePSD"
                type="datetime" placeholder="选择日期时间" default-time="12:00:00">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划完成日期" prop="planCompleteDate">
              <el-date-picker v-model="form.planCompleteDate" :picker-options="pickerOptionsEnd" @change="changePCD"
                type="datetime" placeholder="选择日期时间" default-time="12:00:00">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="登记团队" prop="registrant">
              <el-select v-model="form.registrant" placeholder="请选择登记团队" @change="updateTeam">
                <el-option v-for="item in teamList" :key="item.teamTeamname" :label="item.teamTeamname"
                  :value="item.teamTeamname"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="责任人" prop="duty">
              <el-select v-model="form.duty" placeholder="请选择责任人" @change="updateSelectedUser">
                <el-option v-for="item in userList" :key="item.name" :label="item.name" :value="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="项目状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择项目状态">
                <el-option v-for="dict in dict.type.pro_plan_status" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择项目状态">
                <el-option v-for="dict in dict.type.pro_plan_level" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remake">
          <el-input v-model="form.remake" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="计划工作内容">
          <editor v-model="form.planWorkContent" :min-height="192" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 项目完成对话框 -->
    <el-dialog :title="title" :visible.sync="openS" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="ruless" label-width="150px">

        <el-form-item label="项目完成确认人" prop="planConfirmer">
          <el-select v-model="form.planConfirmer" placeholder="请选择确认人" @change="updateSU">
            <el-option v-for="item in selUserList" :key="item.userName" :label="item.userName"
              :value="item.userName"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmitOk">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listMainten, updateMainten } from "@/api/system/mainten";
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from "@/api/system/plan";
import { listTeam } from "@/api/system/team";
import { listUser } from "@/api/system/user";

export default {
  name: "Plan",
  dicts: ['pro_plan_status', 'pro_plan_level'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目计划表格数据
      planList: [],
      // 员工表格数据
      userList: [],
      // 项目完成确认人表格数据
      selUserList: [],
      // 项目团队管理表格数据
      teamList: [],
      // 项目团队成员表格数据
      proTeamUserList: [],
      // 项目维护表格数据
      maintenList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openS: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        projectName: null,
        planStartDate: null,
        planCompleteDate: null,
        planWorkContent: null,
        actualStartTime: null,
        actualEndTime: null,
        status: null,
        confirmCompleteTime: null,
        workPlanTime: null,
        workCompleteTime: null,
        consumTime: null,
        duty: null,
        registrant: null,
        priority: null,
        childTaskFlag: null,
        planConfirmer: null,
        remake: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '项目名称长度必须介于 2 和 20 之间', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5]+$/, message: '请输入有效的中文', trigger: ['blur', 'change'] }
        ],
        planStartDate: [
          { required: true, message: "计划开始不能为空", trigger: "blur" }
        ],
        planCompleteDate: [
          { required: true, message: "计划完成不能为空", trigger: "blur" }
        ],
        duty: [
          { required: true, message: "责任人不能为空", trigger: "blur" }
        ],
        registrant: [
          { required: true, message: "登记团队不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "项目状态不能为空", trigger: "blur" }
        ],
        priority: [
          { required: true, message: "优先级不能为空", trigger: "blur" }
        ],
        workPlanTime: [
          { required: true, message: "计划用时不能为空", trigger: "blur" }
        ],
      },
      ruless: {
        planConfirmer: [
          { required: true, message: "计划完成确认人不能为空", trigger: "blur" },
        ],
      },
      // 获取选中项目状态
      newStats: 0,
      // 计划开始日期
      // 禁止选择今日时分秒之前的，但可选择今日时分秒之后的，精准到时分秒
      pickerOptionsStart: {
        disabledDate: (time) => {
          // 禁止选择当前时间之前的日期
          return time.getTime() < Date.now(); // 精确到当前时分秒
        }
      },
      // 计划完成日期
      // 禁止 计划完成日期 低于 计划开始日期
      pickerOptionsEnd: {
        disabledDate: (time) => {
          // 禁止选择早于计划开始日期的日期
          return time.getTime() < new Date(this.form.planStartDate).getTime();
        }
      },
    };
  },
  created() {
    this.getList();
    listTeam(this.queryParams).then(response => {
      this.teamList = response.rows;
    });
    listUser(this.queryParams).then(response => {
      this.selUserList = response.rows;
    });
    listMainten(this.queryParams).then(response => {
      this.maintenList = response.rows;
    });
  },
  methods: {
    // 选中预计当前时间
    changePSD() {
      const dateTime = new Date(this.form.planStartDate);
      const formattedDateTime = this.formatDateTime(dateTime);
      this.form.planStartDate = formattedDateTime
    },
    // 选中预计结束时间
    changePCD() {
      const dateTime = new Date(this.form.planCompleteDate);
      const formattedDateTime = this.formatDateTime(dateTime);
      this.form.planCompleteDate = formattedDateTime
    },
    // 转换饿了么组件日期的格式
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 设置返回完成天数
    formatWorkCompleteTime(row, column, cellValue) {
      if (cellValue == 0) {
        return '0天';
      } else if (cellValue == null || cellValue == "") {
        return '';
      } else {
        return `${cellValue}天`;
      }
    },
    // 获取项目确认完成人
    updateSU(selProName) {
      const selInfo = this.selUserList.find(user => user.userName === selProName);
      if (selInfo) {
        this.form.planConfirmer = selProName;
      } else {
        console.error(`未找到项目完成人为 "${selProName}" 的用户`);
        this.form.planConfirmer = '';
      }
    },
    // 获取项目维护信息
    getMainTenInfo() {
      const selInfo = this.maintenList.find(plan => plan.projectId === this.form.projectId);
      if (selInfo) {
        if (this.form.status == 1 && this.form.actualStartTime != null) {
          selInfo.endTime = this.form.actualStartTime
          selInfo.status = 1
        }
        if (this.form.status == 2 && this.form.actualStartTime != null && this.form.actualEndTime != null) {
          selInfo.endTime = this.form.actualStartTime
          selInfo.formalTime = this.form.actualEndTime
          selInfo.status = 4
        }
        if (this.form.status == 2 && this.form.actualEndTime != null) {
          selInfo.formalTime = this.form.actualEndTime
          selInfo.status = 4
        }
        if (this.form.status == 3) {
          selInfo.status = 9
        }
        updateMainten(selInfo).then(response => { });
      } else {
        console.error(`未找到 "${this.form.projectId}" 的项目维护`);
      }
    },
    // 获取完成时间
    DateDiffs(Date_end, Date_start) {
      let oDate1 = new Date(Date_end);
      let oDate2 = new Date(Date_start);
      // 计算两个日期之间的毫秒差异
      let diffInMilliseconds = Math.abs(oDate1 - oDate2);
      // 将毫秒差异转换为天数，包括小数部分
      let diffInDays = diffInMilliseconds / (1000 * 60 * 60 * 24);
      return diffInDays.toFixed(1);
    },
    // 获取当前时间
    getTimes() {
      let date = new Date();
      const year = date.getFullYear();//获取年
      const month = date.getMonth() + 1;//获取月,注意时间是0-11，0代表1月份
      const dates = date.getDate();//获取日
      const hours = date.getHours();//获取小时
      const minute = date.getMinutes();//获取分钟
      const seconds = date.getSeconds();//获取秒钟
      return year + "-" + month + "-" + dates + " " + hours + ":" + minute + ":" + seconds;
    },
    // 获取责任人
    updateSelectedUser(selectedDuty) {
      // 根据选中的责任人名字查找对应的用户对象
      const selInfo = this.userList.find(user => user.name === selectedDuty);
      if (selInfo) {
        // 更新表单中的责任人名字和责任人ID
        this.form.duty = selectedDuty;
        this.form.userId = selInfo.userId;
      } else {
        // 如果没有找到匹配的用户（理论上不应该发生，除非数据不一致），可以重置表单字段或进行错误处理
        console.error(`未找到责任人为 "${selectedDuty}" 的用户`);
        this.form.duty = '';
        this.form.userId = '';
      }
    },
    // 获取登记团队
    updateTeam(selectedDuty) {
      const selInfo = this.teamList.find(team => team.teamTeamname === selectedDuty);
      if (selInfo) {
        this.form.registrant = selectedDuty;
        this.userList = selInfo.proTeamUserList;
        this.form.duty = '';
      } else {
        console.error(`未找到登记团队为 "${selectedDuty}" 的信息`);
        this.form.registran = '';
        this.userList = [];
      }
    },
    /** 查询项目计划列表 */
    getList() {
      this.loading = true;
      listPlan(this.queryParams).then(response => {
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openS = false;
      this.reset();
      this.userList = [];
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: null,
        projectName: null,
        planStartDate: null,
        planCompleteDate: null,
        planWorkContent: null,
        actualStartTime: null,
        actualEndTime: null,
        status: null,
        confirmCompleteTime: null,
        workPlanTime: null,
        workCompleteTime: null,
        consumTime: null,
        duty: null,
        registrant: null,
        priority: null,
        childTaskFlag: null,
        planConfirmer: null,
        remake: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.userList = [];
      this.open = true;
      this.title = "添加项目计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.updateTeam(row.registrant);
      const projectId = row.projectId || this.ids
      getPlan(projectId).then(response => {
        this.form = response.data;
        this.newStats = this.form.status
        this.open = true;
        this.title = "修改项目计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (this.form.status == 1 && this.form.actualStartTime == null) {
          this.form.actualStartTime = this.getTimes();
        } else if (this.form.status == 2 && this.form.actualStartTime == null && this.form.actualEndTime == null) {
          this.form.actualStartTime = this.getTimes();
          this.form.actualEndTime = this.getTimes();
          const startDate = this.form.actualStartTime;
          const endDate = this.form.actualEndTime;
          const daysDiff = this.DateDiffs(endDate, startDate);
          this.form.workCompleteTime = daysDiff
        } else if (this.form.status == 2 && this.form.actualEndTime == null) {
          this.form.actualEndTime = this.getTimes();
          const startDate = this.form.actualStartTime;
          const endDate = this.form.actualEndTime;
          const daysDiff = this.DateDiffs(endDate, startDate);
          this.form.workCompleteTime = daysDiff
        }
        if (valid) {
          if (this.form.projectId != null) {
            if (this.newStats == 1) {
              if (this.form.status == 0) {
                this.$modal.msgError("已启动计划禁止改回计划");
                return
              }
            } else if (this.newStats == 2) {
              if (this.form.status == 0) {
                this.$modal.msgError("已完成计划禁止改回计划");
                return
              }
              if (this.form.status == 1) {
                this.$modal.msgError("已完成计划禁止改回启动");
                return
              }
            } else if (this.newStats == 3) {
              this.$modal.msgError("已取消计划禁止修改");
              return
            }
            updatePlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.openS = false;
              this.getList();
            });
          } else {
            console.log("添加if");
            addPlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId || this.ids;
      this.$modal.confirm('是否确认删除项目计划编号为"' + projectIds + '"的数据项？').then(function () {
        return delPlan(projectIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 项目完成按钮操作 */
    handleOk(row) {
      this.reset();
      const projectId = row.projectId || this.ids
      getPlan(projectId).then(response => {
        this.form = response.data;
        this.newStats = this.form.status
        this.openS = true;
        this.title = "项目计划完成";
      });
    },
    /** 提交按钮 */
    handleSubmitOk() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.projectId != null) {
            if (this.newStats == 0) {
              if (this.form.workCompleteTime == null || this.form.workCompleteTime == "") {
                this.$modal.msgError("项目计划未完成，禁止确认完成项目。");
                return
              }
            } else if (this.newStats == 1) {
              if (this.form.workCompleteTime == null || this.form.workCompleteTime == "") {
                this.$modal.msgError("项目计划未完成，禁止确认完成项目。");
                return
              }
            } else if (this.newStats == 3) {
              this.$modal.msgError("已取消计划禁止完成");
              return
            } else {
              this.form.confirmCompleteTime = this.getTimes();
              updatePlan(this.form).then(response => {
                this.$modal.msgSuccess("确认成功");
                this.openS = false;
                this.getList();
              });
            }
          } else {
            this.$modal.msgSuccess("项目ID为空，确认失败。");
          }
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
